package user

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"practice/config"
	"practice/internal/model/dao"
	"practice/tools"
	"time"
)

type Logins struct {
	Mobile   string `form:"mobile" json:"mobile" xml:"mobile"  binding:"required,mobile"`
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

func Login(c *gin.Context) {
	var json Logins
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	mobile := json.Mobile
	password := json.Password
	var users dao.User
	config.DB.Where("mobile=?", mobile).First(&users)
	if users.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "该用户未注册,请注册"})
		return
	}
	if tools.MD5(password) != users.Password {
		c.JSON(http.StatusBadRequest, gin.H{"error": "密码错误"})
		return
	}
	//生成token
	jwtSign := tools.NewJWT(config.AppConfig.Jwt.Key)
	tokenClaims := tools.CustomClaims{
		ID:       users.ID,
		NickName: users.Mobile,
		Mobile:   users.Mobile,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + config.AppConfig.Jwt.Expiry,
			Subject:   "userAccess",
		},
	}
	token, err := jwtSign.CreateToken(tokenClaims)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "token生成失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "登录成功",
		"data": token,
	})

}

// 解析token
func ParseToken(c *gin.Context) {
	//tokenStr := c.GetHeader("Authorization")
	//token := strings.Split(tokenStr, " ")
	//jwtSign := tools.NewJWT(config.AppConfig.Jwt.Key)
	//data, err := jwtSign.ParseToken(token[1])
	//if err != nil {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"error": "解析失败",
	//	})
	//	return
	//}
	data, _ := c.Get("claims")
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": data,
	})
}
